<script setup lang="ts">
import { message } from 'ant-design-vue';
import axios from 'axios';
import { computed, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router'; // 获取路由参数
import CourseFolderInfo from '@/views/Square/LearningSquare/Course/details/components/CourseFolderInfo.vue';
import type { CourseInfo } from '@/views/Square/LearningSquare/Course/details/CourseInfo';
// 使用路由获取参数
const route = useRoute();
const courseId = ref(route.params.courseId);

// 课程信息
const courseInfo = ref<CourseInfo | null>(null);
const isUpvote = ref(false); // 是否已点赞
const isFavorite = ref(false); // 是否已收藏
const loadingFavorite = ref(true); // 判断收藏状态是否加载完成
const teacherName = ref('');
const teacherImage = ref('');
const teacherJob = ref('');
const teacherTitle = ref('');
const teacherSchool = ref('');

// 添加一个计算属性来判断是否有教师信息
const isTeacherInfoExit = computed(() => {
  return teacherName.value || teacherImage.value || teacherJob.value
         || teacherTitle.value || teacherSchool.value;
});

// 获取 Cookie 值的函数
const getCookieValue = (name: string): string | null => {
  const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
  return match ? decodeURIComponent(match[2]) : null;
};

// 获取 Axios 配置
const getAxiosConfig = () => {
  const accessToken_java = getCookieValue('access_token_lf');
  return {
    headers: {
      "Authorization": `Bearer ${accessToken_java}`,
      'Content-Type': 'application/json',
    },
    params: { courseId: courseId.value },
  };
};

// 获取课程信息
const fetchCourseInformation = async () => {
  const axiosConfig = getAxiosConfig();

  try {
    const response = await axios.get('/java/ground/study/course/get_course_information_by_id', axiosConfig);
    if (response.status === 200) {
      courseInfo.value = response.data.data; // 使用响应数据
      isUpvote.value = response.data.userHasLiked; // 设置用户是否已经点赞
      const teacher = courseInfo.value?.teacher?.[0] ?? null;
      teacherName.value = teacher?.teacherName ?? '';
      teacherImage.value = teacher?.teacherImage ?? '';
      teacherJob.value = teacher?.teacherJob ?? '';
      teacherTitle.value = teacher?.teacherTitle ?? '';
      teacherSchool.value = teacher?.teacherSchool ?? '';
    }
  }
  catch (error) {
    message.error('获取课程信息失败');
  }
};

// 检查是否收藏
const checkIfFavorited = async () => {
  try {
    const response = await axios.get('/java/ground/study/course/get_favorite_list', {
      headers: {
        "Authorization": `Bearer ${getCookieValue('access_token_lf')}`,
        'Content-Type': 'application/json',
      },
    });

    if (response.status === 200 && response.data.code === 200) {
      const favoriteCourses = response.data.data;
      isFavorite.value = favoriteCourses.some((course: { courseId: string }) => course.courseId === courseId.value);
    }
  }
  catch (error) {
    message.error('获取收藏信息失败');
  }
  finally {
    loadingFavorite.value = false; // 收藏状态加载完成
  }
};

// 处理点赞
const handleLike = async () => {
  if (isUpvote.value) {
    message.warning('您已经点过赞了');
    return;
  }

  try {
    await axios.post('/java/ground/study/course/add_course_like', {
      courseId: courseId.value,
    }, {
      headers: {
        "Authorization": `Bearer ${getCookieValue('access_token_lf')}`,
        'Content-Type': 'application/json',
      },
    });

    if (courseInfo.value)
      courseInfo.value.viewNum = String(Number(courseInfo.value.viewNum || 0) + 1);

    isUpvote.value = true;
  }
  catch (error) {
    message.error('点赞请求失败');
  }
};

// 处理收藏和取消收藏
const handleFavorite = async () => {
  try {
    if (isFavorite.value) {
      // 取消收藏
      await axios.post('/java/ground/study/course/remove_course_collection', {
        courseId: courseId.value,
      }, {
        headers: {
          "Authorization": `Bearer ${getCookieValue('access_token_lf')}`,
          'Content-Type': 'application/json',
        },
      });
      isFavorite.value = false; // 更新收藏状态
      message.success('已取消收藏');
    }
    else {
      // 添加收藏
      await axios.post('/java/ground/study/course/add_course_collection', {
        courseId: courseId.value,
      }, {
        headers: {
          "Authorization": `Bearer ${getCookieValue('access_token_lf')}`,
          'Content-Type': 'application/json',
        },
      });
      isFavorite.value = true; // 更新收藏状态
      message.success('已收藏课程');
    }
  }
  catch (error) {
    message.error('操作失败，请稍后再试');
  }
};

// 生命周期钩子
onMounted(async () => {
  await fetchCourseInformation();
  await checkIfFavorited();
});
</script>

<template>
  <a-layout v-if="courseInfo" class="bg-transparent h-full flex flex-col mt-2">
    <a-breadcrumb style="font-weight: bold; margin: 0rem 1rem;" class="text-3xl">
      <a-breadcrumb-item>
        <router-link to="/user/learningNew/skill-tree" style="height: 100%;">
          学习广场
        </router-link>
      </a-breadcrumb-item>

      <a-breadcrumb-item>
        <router-link to="/user/learningNew/course" style="height: 100%;">
          课程
        </router-link>
      </a-breadcrumb-item>

      <a-breadcrumb-item class="flex items-center relative">
        详情
        <img
          src="@/assets/title_star.svg"
          alt="详情"
          class="w-6 h-6 absolute -right-6"
        >
      </a-breadcrumb-item>
    </a-breadcrumb>

    <div class="flex flex-row mt-2">
      <div :class="[isTeacherInfoExit ? 'w-[80%]' : 'w-full']" class="bg-transparent h-full">
        <div class="bg-white mx-4 rounded-lg h-full">
          <div class="text-xl font-bold flex flex-row justify-between items-center p-2 pb-0">
            <p class="flex-grow my-0">
              {{ courseInfo.courseName }}
            </p>

            <div class="flex flex-row gap-2">
              <a-button :disabled="isUpvote" @click="handleLike">
                赞 {{ courseInfo.viewNum }}
              </a-button>

              <a-button :disabled="loadingFavorite" @click="handleFavorite">
                {{ loadingFavorite ? '加载中...' : (isFavorite ? '已收藏' : '收藏') }}
              </a-button>
            </div>
          </div>

          <div class="mx-2 mt-2">
            <a-tag>
              {{ courseInfo.courseTag }}
            </a-tag>
          </div>

          <div class="mx-2 mt-2 pb-2">
            <p class="text-lg my-0">
              {{ courseInfo.courseDescription }}
            </p>
          </div>
        </div>
      </div>

      <div v-if="isTeacherInfoExit" class="w-[20%] bg-transparent h-full">
        <div class="bg-white rounded-lg mr-4 h-full flex flex-row items-center pl-4">
          <img
            v-if="teacherImage"
            :src="teacherImage"
            :alt="teacherName"
            style="width: 80px; height: 80px; object-fit: cover; border-radius: 50%;"
          >
          <div class="ml-4">
            <p class="text-2xl font-bold my-0">
              {{ teacherName }}
            </p>
            <p class="text-lg my-0">
              {{ teacherJob }}, {{ teacherTitle }}
            </p>
            <p class="text-lg my-0">
              {{ teacherSchool }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <div class="m-4 flex-grow flex flex-col overflow-auto">
      <p class="text-xl font-bold my-0 mb-2">
        课程目录
      </p>
      <div class="flex-grow overflow-auto">
        <CourseFolderInfo />
      </div>
    </div>
  </a-layout>
</template>

<style scoped lang="scss">

</style>
